<template>
  <!-- 职业测评，已解锁状态 -->
  <page-wrap
    title="职业测评"
    ref="pageWrap"
    hideTab
    back
    :showTop="showTop"
    hideSafeArea
    :bg-color="uNavColor"
  >
    <view class="wrapper" style="height: 100vh">
      <view
        class="tab-wrapper"
        :style="{ paddingTop: navHeight + 'px', backgroundColor: uNavColor }"
      >
        <u-tabs
          class="tabsList"
          :current="currentIndex"
          name="tagName"
          :list="tabList"
          @change="handleChangeTabs"
          height="55"
          :active-item-style="activeItemStyle"
          :bg-color="transform"
          :gutter="24"
          :bar-style="barStyle"
          font-size="28"
          :inactive-color="'#75957f'"
        ></u-tabs>
      </view>
      <scroll-view
        class="scroll"
        :style="{ paddingTop: scrollPaddingTop + 'px' }"
        :scroll-y="true"
        :overflow-x="false"
        :scroll-with-animation="true"
        :scroll-into-view="scrollIntoViewId"
        @scroll="handleScrollEvent"
        @scrolltoupper="handleScrollToTop"
      >
        <image
          :src="coverImgUrl"
          :style="[{ width: '750rpx' }, { height: '1287rpx' }]"
        />
        <view id="personalityAttributes">
          <!-- 性格属性  -->
          <PersonalityAttributes :dataItem="personalityAttributes" />
        </view>
        <view id="personalityFeature">
          <!-- 性格特征 -->
          <PersonalityFeature :dataItem="personalityTraits" />
        </view>
        <view id="personalityAdvantages">
          <!-- 性格优势 -->
          <PersonalityAdvantage :dataItem="personalityAdvantages" />
        </view>
        <view id="personalityDisadvantages">
          <!-- 性格劣势 -->
          <PersonalityDisadvantage :dataItem="personalityDisadvantages" />
        </view>
        <view id="typicalFigure">
          <!-- 代表人物 -->
          <RepresentativePersonage :dataItem="typicalFigure" />
        </view>
        <view id="personalityRelation">
          <!-- 性格关系 -->
          <PersonalityRelation :dataItem="personalityRelation" />
        </view>
        <view id="workPotential">
          <!-- 工作潜能 -->
          <WorkPotential :dataItem="workPotential" />
        </view>
        <view id="workEnvironment">
          <!-- 工作环境 -->
          <WorkEnvironment :dataItem="workEnvironment" />
        </view>
        <view id="workBeliefs">
          <!-- 职业价值观 -->
          <WorkBeliefs :dataItem="workValues" />
        </view>
        <view id="relatedPosition">
          <!-- 关联职业 -->
          <RelatedPosition :dataItem="relatedMajors" />
        </view>
        <view id="relatedMajor">
          <!-- 关联专业 -->
          <RelatedMajor :dataItem="relatedProfessions" />
        </view>
        <image
          src="https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/bg_end.png"
          :style="[{ width: '750rpx' }, { height: '260rpx' }]"
        />
      </scroll-view>
      <view class="footer">
        <!-- 如果是来自双选会，只显示返回首页按钮，返回双选会首页 -->
        <template v-if="fromSxh == 'sxh'">
          <view :class="['btn']" @click="handleReturn">返回首页</view>
        </template>
        <!-- 如果是来自双选会的扫码，也显示返回首页按钮 -->
        <template v-else-if="fromSxh == 'fromSxhQrCode'">
          <view
            :class="[leftUseNum > 0 ? 'btn-half' : 'btn']"
            @click="handleReturn"
            >返回首页</view
          >
          <view
            v-if="leftUseNum > 0"
            class="btn-half ml-14 active"
            @click="handleRetest"
            >再测一次</view
          >
        </template>
        <!-- 如果是来自其他情景，就显示两个按钮 -->
        <template v-else>
          <view v-if="fromWhere == 'miniprogramZty'" class="btn" @click="goBack"
            >返回首页</view
          >
          <view v-else-if="leftUseNum > 0" class="btn" @click="handleRetest"
            >再测一次</view
          >
        </template>
      </view>
    </view>
  </page-wrap>
</template>

<script>
import { throttle } from "lodash";

import PersonalityAttributes from "./PersonalityAttributes.vue";
import PersonalityFeature from "./PersonalityFeature.vue";
import PersonalityAdvantage from "./PersonalityAdvantage.vue";
import PersonalityDisadvantage from "./PersonalityDisadvantage.vue";
import RepresentativePersonage from "./RepresentativePersonage.vue";
import PersonalityRelation from "./PersonalityRelation.vue";
import WorkPotential from "./WorkPotential.vue";
import WorkEnvironment from "./WorkEnvironment.vue";
import WorkBeliefs from "./WorkBeliefs.vue";
import RelatedMajor from "./RelatedMajor.vue";
import RelatedPosition from "./RelatedPosition.vue";

import { getDivineBeastCover } from "@/utils/handle";
import { careerAssessRegularInfoNew } from "@/utils/data";
import { start } from "@/api/modules/activity";
export default {
  components: {
    PersonalityAttributes,
    PersonalityFeature,
    PersonalityAdvantage,
    PersonalityDisadvantage,
    RepresentativePersonage,
    PersonalityRelation,
    WorkPotential,
    WorkEnvironment,
    WorkBeliefs,
    RelatedMajor,
    RelatedPosition,
  },
  props: {
    scrollRes: {
      type: Object,
      default: function () {
        return {};
      },
    },
    resultInfo: {
      type: Object,
      default: function () {
        return {};
      },
    },
    fromSxh: {
      type: String,
      default: "",
    },
    fromWhere: {
      type: String,
      default: "",
    },
    leftUseNum: {
      type: Number,
      default: 0,
    },
    toBook: {
      type: String,
      default: "false",
    },
    personId: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      uNavColor: "transparent",
      tabsListBgColor: "transparent",
      navHeight: getApp().globalData.navHeight,
      activeItemStyle: careerAssessRegularInfoNew.activeItemStyle,
      barStyle: careerAssessRegularInfoNew.barStyle,
      coverImgUrl: careerAssessRegularInfoNew.coverImgUrl,
      tabList: careerAssessRegularInfoNew.tabList,

      // 是否是通过点击切换模块
      isChangeTabByClick: false,
      currentScrollTop: 0,
      scrollIntoViewId: "",
      timeoutId: null,
      scrollPaddingTop: 0,
      currentIndex: 0,
      showTop: false,

      personalityAttributes: {}, // 性格属性
      personalityTraits: {}, // 性格特征
      personalityRelation: {}, // 性格关系
      personalityAdvantages: [], // 性格优势
      personalityDisadvantages: [], // 性格劣势
      typicalFigure: {}, // 代表人物
      relatedMajors: [], // 相关职业
      relatedProfessions: [], // 相关专业
      workEnvironment: {}, // 工作环境
      workPotential: {}, // 工作潜能
      workValues: {},
      componentsHeightList: [],
      componentsList: [
        "personalityAttributes",
        "personalityFeature",
        "personalityAdvantages",
        "personalityDisadvantages",
        "typicalFigure",
        "personalityRelation",
        "workPotential",
        "workEnvironment",
        "workBeliefs",
        "relatedPosition",
        "relatedMajor",
      ],
    };
  },

  watch: {
    resultInfo: {
      handler(val) {
        const contentV2 = val.contentV2;
        this.personalityAttributes = contentV2.personalityAttributes;
        this.personalityRelation = contentV2.personalityRelation;
        this.personalityAdvantages = contentV2.personalityAdvantages;
        this.personalityDisadvantages = contentV2.personalityDisadvantages;
        this.personalityTraits = contentV2.personalityTraits;
        this.relatedMajors = contentV2.relatedMajors;
        this.relatedProfessions = contentV2.relatedProfessions;
        this.typicalFigure = contentV2.typicalFigure;
        this.workEnvironment = contentV2.workEnvironment;
        this.workPotential = contentV2.workPotential;
        this.workValues = contentV2.workValues;
        this.coverImgUrl = getDivineBeastCover(val.dataType);
        console.log(this.leftUseNum, "leftUseNum-======");
      },
      deep: true,
      immediate: true,
    },
  },
  onReady() {},
  created() {},
  mounted() {
    this.getHeight();
    if (this.fromWhere == "miniprogramZty") {
      uni.removeStorageSync("SxhPersonId");
    }
  },

  methods: {
    goBack() {
      uni.navigateBack();
    },
    handleRetest() {
      const params = {
        personId: uni.getStorageSync("person-id").slice(2),
        assessmentType: 0,
        assessmentVersion: 2, // 测评版本 1:v1版本 2：v2版本，只要是点击了答题，都是v2版本
      };
      start(params).then((res) => {
        if (res.code == 200) {
          if (res.data) {
            this.resultId = res.data.id;
            wx.setStorageSync("assessmentId", this.resultId);
            //跳答题列表
            uni.navigateTo({
              url: `/pagesSub/career/activity/vocationalAssessmentAnswer?fromSxh=${this.fromSxh}`,
            });
          }
        }
      });
    },
    handleReturn() {
      if (this.fromSxh == "sxh") {
        uni.reLaunch({ url: "/pagesSub/doubleChannelChoosingMeeting/index" });
        return;
      }
      if (this.fromSxh == "fromSxhQrCode") {
        uni.reLaunch({ url: "/pagesSub/userCenter/careerPathV2/index" });
        return;
      }
    },
    handleScrollEvent: throttle(function (e) {
      const { scrollTop } = e.detail;
      if (scrollTop > 50) {
        this.showTop = true;
        this.uNavColor = "#cae8ba";
      } else {
        this.showTop = false;
        this.uNavColor = "transparent";
      }
      if (this.isChangeTabByClick) {
        this.isChangeTabByClick = false;
        return;
      }
      // 找到位于顶部元素的索引，距离大于滚动高度的第一个元素的上一个元素就是此时位于顶部的元素
      let index =
        this.componentsHeightList.findIndex((item) => {
          // 滚动条的位置大于元素距离顶部位置的距离时，说明元素已经滑过了顶部
          return item > scrollTop + 135;
        }) - 1;
      if (index == this.currentIndex) return;
      this.currentIndex = index;
    }, 100),
    getHeight() {
      setTimeout(() => {
        this.componentsList.forEach((item) => {
          const query = uni.createSelectorQuery().in(this);
          query
            .select(`#${item}`)
            .boundingClientRect((e) => {
              this.componentsHeightList.push(e.top);
            })
            .exec();
        });
        console.log(this.componentsHeightList, "componentsList");
      }, 2000);
    },
    handleScrollToTop() {
      this.scrollPaddingTop = 0;
    },
    handleChangeTabs(index) {
      this.isChangeTabByClick = true;
      this.currentIndex = index;
      this.scrollPaddingTop = this.navHeight + 40;
      this.scrollIntoViewId = this.componentsList[index];
      clearTimeout(this.timeoutId);
      this.timeoutId = setTimeout(() => {
        this.scrollIntoViewId = "";
      }, 300);
    },
  },
};
</script>

<style lang="scss" scoped>
.wrapper {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
  .tab-wrapper {
    position: fixed;
    z-index: 999;
    width: 100%;
    background: transparent;
  }
  .scroll {
    height: 100%;
    width: 100%;
    background: url($img-base + "career/careerAssessResult/base_bg.png")
      no-repeat;
    background-size: 100% 100%;
  }
  .footer {
    position: fixed;
    left: 32rpx;
    bottom: 40rpx;
    width: calc(100vw - 64rpx);
    z-index: 999;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .btn,
    .btn-half {
      color: #fff;
      font-size: 32rpx;
      text-align: center;
      background: #fe7220;
    }
    .btn {
      border-radius: 50rpx;
      width: 100%;
    }
    .btn-half {
      padding: 26rpx 0;
      border-radius: 50rpx;
      width: calc(50% - 12rpx);
    }
    .ml-14 {
      margin-left: 14rpx;
    }
    .active {
      color: #fff;
      background: #28cc75;
    }
  }
}
</style>
